package com.example.orderservice.controller;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.pattern.Patterns;
import akka.util.Timeout;
import com.example.orderservice.actor.PersistentOrderActor;
import com.example.orderservice.event.OrderItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletionStage;

/**
 * 订单控制器
 * 提供REST API接口，通过Akka Actor处理订单业务
 */
@Slf4j
@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @Autowired
    private ActorSystem actorSystem;

    private final Timeout timeout = Timeout.create(Duration.ofSeconds(5));

    /**
     * 创建订单
     */
    @PostMapping
    public ResponseEntity<String> createOrder(@RequestBody CreateOrderRequest request) {
        try {
            log.info("收到创建订单请求: {}", request);
            
            // 创建PersistentOrderActor
            ActorRef orderActor = actorSystem.actorOf(PersistentOrderActor.props(), "order-" + request.getOrderId());
            
            // 构建创建订单命令
            PersistentOrderActor.CreateOrder createOrderCmd = new PersistentOrderActor.CreateOrder(
                request.getOrderId(),
                request.getCustomerId(),
                request.getItems(),
                request.getTotalAmount()
            );
            
            // 发送命令并等待响应
            CompletionStage<Object> future = Patterns.ask(orderActor, createOrderCmd, timeout);
            
            return future.thenApply(response -> {
                PersistentOrderActor.OrderCreated result = (PersistentOrderActor.OrderCreated) response;
                if ("SUCCESS".equals(result.getStatus())) {
                    return ResponseEntity.ok("订单创建成功: " + result.getOrderId());
                } else {
                    return ResponseEntity.badRequest().body("订单创建失败: " + result.getOrderId());
                }
            }).toCompletableFuture().get();
            
        } catch (Exception e) {
            log.error("创建订单异常: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError().body("创建订单异常: " + e.getMessage());
        }
    }

    /**
     * 支付订单
     */
    @PostMapping("/{orderId}/pay")
    public ResponseEntity<String> payOrder(
            @PathVariable String orderId,
            @RequestBody PayOrderRequest request) {
        try {
            log.info("收到支付订单请求: orderId={}, request={}", orderId, request);
            
            ActorRef orderActor = actorSystem.actorOf(PersistentOrderActor.props(), "order-" + orderId);
            
            PersistentOrderActor.PayOrder payOrderCmd = new PersistentOrderActor.PayOrder(
                orderId,
                request.getPaymentId(),
                request.getPaymentMethod(),
                request.getAmount()
            );
            
            CompletionStage<Object> future = Patterns.ask(orderActor, payOrderCmd, timeout);
            
            return future.thenApply(response -> {
                PersistentOrderActor.OrderPaid result = (PersistentOrderActor.OrderPaid) response;
                if ("SUCCESS".equals(result.getStatus())) {
                    return ResponseEntity.ok("订单支付成功: " + result.getOrderId());
                } else {
                    return ResponseEntity.badRequest().body("订单支付失败: " + result.getOrderId());
                }
            }).toCompletableFuture().get();
            
        } catch (Exception e) {
            log.error("支付订单异常: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError().body("支付订单异常: " + e.getMessage());
        }
    }

    /**
     * 获取订单状态
     */
    @GetMapping("/{orderId}")
    public ResponseEntity<String> getOrderStatus(@PathVariable String orderId) {
        try {
            log.info("获取订单状态: {}", orderId);
            
            ActorRef orderActor = actorSystem.actorOf(PersistentOrderActor.props(), "order-" + orderId);
            
            PersistentOrderActor.GetOrderStatus getStatusCmd = new PersistentOrderActor.GetOrderStatus(orderId);
            
            CompletionStage<Object> future = Patterns.ask(orderActor, getStatusCmd, timeout);
            
            return future.thenApply(response -> {
                PersistentOrderActor.OrderStatus result = (PersistentOrderActor.OrderStatus) response;
                PersistentOrderActor.OrderState state = result.getState();
                
                if (state.getOrderId() == null) {
                    return ResponseEntity.notFound().build();
                }
                
                return ResponseEntity.ok(String.format(
                    "订单ID: %s, 状态: %s, 客户ID: %s, 总金额: %s, 创建时间: %s",
                    state.getOrderId(), state.getStatus(), state.getCustomerId(),
                    state.getTotalAmount(), state.getCreatedAt()
                ));
            }).toCompletableFuture().get();
            
        } catch (Exception e) {
            log.error("获取订单状态异常: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError().body("获取订单状态异常: " + e.getMessage());
        }
    }

    /**
     * 取消订单
     */
    @PostMapping("/{orderId}/cancel")
    public ResponseEntity<String> cancelOrder(
            @PathVariable String orderId,
            @RequestBody CancelOrderRequest request) {
        try {
            log.info("收到取消订单请求: orderId={}, reason={}", orderId, request.getReason());
            
            ActorRef orderActor = actorSystem.actorOf(PersistentOrderActor.props(), "order-" + orderId);
            
            PersistentOrderActor.CancelOrder cancelOrderCmd = new PersistentOrderActor.CancelOrder(
                orderId,
                request.getReason()
            );
            
            CompletionStage<Object> future = Patterns.ask(orderActor, cancelOrderCmd, timeout);
            
            return future.thenApply(response -> {
                PersistentOrderActor.OrderCancelled result = (PersistentOrderActor.OrderCancelled) response;
                if ("SUCCESS".equals(result.getStatus())) {
                    return ResponseEntity.ok("订单取消成功: " + result.getOrderId());
                } else {
                    return ResponseEntity.badRequest().body("订单取消失败: " + result.getOrderId());
                }
            }).toCompletableFuture().get();
            
        } catch (Exception e) {
            log.error("取消订单异常: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError().body("取消订单异常: " + e.getMessage());
        }
    }

    // 请求DTO类
    public static class CreateOrderRequest {
        private String orderId;
        private String customerId;
        private List<com.example.orderservice.event.OrderItem> items;
        private Double totalAmount;

        // Constructors, getters, setters
        public CreateOrderRequest() {}

        public CreateOrderRequest(String orderId, String customerId, List<com.example.orderservice.event.OrderItem> items, Double totalAmount) {
            this.orderId = orderId;
            this.customerId = customerId;
            this.items = items;
            this.totalAmount = totalAmount;
        }

        public String getOrderId() { return orderId; }
        public void setOrderId(String orderId) { this.orderId = orderId; }
        public String getCustomerId() { return customerId; }
        public void setCustomerId(String customerId) { this.customerId = customerId; }
        public List<com.example.orderservice.event.OrderItem> getItems() { return items; }
        public void setItems(List<com.example.orderservice.event.OrderItem> items) { this.items = items; }
        public Double getTotalAmount() { return totalAmount; }
        public void setTotalAmount(Double totalAmount) { this.totalAmount = totalAmount; }
    }

    public static class PayOrderRequest {
        private String paymentId;
        private String paymentMethod;
        private Double amount;

        // Constructors, getters, setters
        public PayOrderRequest() {}

        public PayOrderRequest(String paymentId, String paymentMethod, Double amount) {
            this.paymentId = paymentId;
            this.paymentMethod = paymentMethod;
            this.amount = amount;
        }

        public String getPaymentId() { return paymentId; }
        public void setPaymentId(String paymentId) { this.paymentId = paymentId; }
        public String getPaymentMethod() { return paymentMethod; }
        public void setPaymentMethod(String paymentMethod) { this.paymentMethod = paymentMethod; }
        public Double getAmount() { return amount; }
        public void setAmount(Double amount) { this.amount = amount; }
    }

    public static class CancelOrderRequest {
        private String reason;

        // Constructors, getters, setters
        public CancelOrderRequest() {}

        public CancelOrderRequest(String reason) {
            this.reason = reason;
        }

        public String getReason() { return reason; }
        public void setReason(String reason) { this.reason = reason; }
    }
}
